package com.cssw.fyzb.wap.util;

import com.sun.crypto.provider.SunJCE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.security.Security;

/**
 * @author Feng Chen
 */
public abstract class AesUtil {

    private AesUtil() {

    }

    public static final String AES_KEY = "aim";

    public static final Logger logger = LoggerFactory.getLogger(AesUtil.class);

    /**
     * 加密
     *
     * @param plainText
     * @return
     */
    public static String encode(String plainText) {
        try {
            Security.addProvider(new SunJCE());
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(AES_KEY.getBytes());
            keygen.init(128, secureRandom);
            SecretKey desKey = keygen.generateKey();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, desKey);
            byte[] bytes = cipher.doFinal(plainText.getBytes());
            return Base64Util.encode(HexUtil.byteArrayToHex(bytes));
        } catch (Exception e) {
            logger.error("", e);
        }
        return null;
    }

    /**
     * 解密
     *
     * @param cipherText
     * @return
     */
    public static String decode(String cipherText) {
        try {
            Security.addProvider(new SunJCE());
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(AES_KEY.getBytes());
            keygen.init(128, secureRandom);
            SecretKey desKey = keygen.generateKey();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, desKey);
            byte[] bytes = cipher.doFinal(HexUtil.hexToByteArray(Base64Util.decode(cipherText)));
            return new String(bytes);
        } catch (Exception e) {
            logger.error("", e);
        }
        return null;
    }

}
